package exemplo.faces;

import java.sql.SQLException;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import exemplo.database.ProductDAO;
import exemplo.model.Product;

public class ProductConverter implements Converter{

	private ProductDAO prodDAO;
	
	public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
		try {
			prodDAO = new ProductDAO();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		int code = Integer.parseInt(arg2);
		try {
			return prodDAO.getByCode(code);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
		Product prod = (Product) arg2;
		return String.valueOf(prod.getCode());
	}
	
	

}
